/*
 * author      : 吴中勤 
 * date        : 2018/8/11
 * description : TODO
 */

package com.deepexi.adapter.common;

import io.undertow.Undertow;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorldServer {

    private static Logger logger = LoggerFactory.getLogger(HelloWorldServer.class);

    private Undertow server;
    private Thread serverThread;

    /*
 * Creating HttpHandlers as a method and passing it as a method reference is pretty clean.
 * This also helps reduce accidentally adding state to handlers.
 */
    protected static void helloWorldHandler(HttpServerExchange exchange) {
        exchange
                .getResponseHeaders()
                .add(Headers.CONTENT_TYPE, "application/json");

        exchange
                .getResponseSender()
                .send("{\"code\":\"0\"}");
    }

    protected void startServer() {
        int port = 8080;
        /*
         *  "localhost" will ONLY listen on local host.
         *  If you want the server reachable from the outside you need to set "0.0.0.0"
         */
        String host = "0.0.0.0";

        /*
         * This web server has a single parser with no routing.
         * ALL urls are handled by the helloWorldHandler.
         */
        server = Undertow.builder()
                // Add the helloWorldHandler as a method reference.
                .addHttpListener(port, host, HelloWorldServer::helloWorldHandler)
                .build();
        if (logger.isDebugEnabled()) {
            logger.debug("starting on http://" + host + ":" + port);
        }

        serverThread = new Thread(() -> {
            server.start();
        });
        serverThread.start();
    }

    //
    protected void stopServer() {
        if (server == null) return;
        //
        server.stop();
        serverThread.stop();
    }
}
